package com.xszn.middleware.socket;

import com.xszn.middleware.util.CommenUtil;
import com.xszn.middleware.util.SemaphoreUtils;
import com.xszn.middleware.util.WebSocketUsers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;


@Component
@ServerEndpoint("/xszn/start/{brand}/{type}")
public class Start {
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Start.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * brand 品牌  设备型号
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("brand") String brand,@PathParam("type") String type) throws Exception
    {

       boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            session.close();
        }
        else
        {
            String deviceId = CommenUtil.getSessionId(session);
            // 添加用户
            WebSocketUsers.put(deviceId, session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());

        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        String deviceId = CommenUtil.getSessionId(session);
        // 移除用户
        WebSocketUsers.remove(deviceId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        String deviceId = CommenUtil.getSessionId(session);

        LOGGER.info("\n 连接异常 - {}", deviceId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(deviceId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     *
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session)
    {
        CommenUtil.keepLive(session, message);
        LOGGER.info("服务收到消息：" + message);
//        WebSocketUsers.sendMessageToUserByText(session, message   );
    }
}
